package app.netant;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import app.client.netant.NetAnt;
import cn.lily.com.db.sql.DBManager;
import cn.lily.com.db.sql.manager.DBOfflineManager;

public class NetAntBase {
	
	/**
	 * 爬虫类
	 */
	protected NetAnt netAnt;
	
	/**
	 * 爬取网址
	 */
	protected String netSite;
	
	protected int timeout = 2000;
	
	/**
	 * 爬取文档
	 */
	protected Document document;
	
	public NetAntBase(String netSite){		
		this.netSite = netSite;
		NetAnt netAnt = new NetAnt(netSite, this.timeout);
		this.document = netAnt.getDocument();
	}
	
	public NetAntBase(String netSite,int timeout){
		this.netSite = netSite;
		this.timeout = timeout;
		NetAnt netAnt = new NetAnt(netSite, this.timeout);
		this.document = netAnt.getDocument();
	}
	
	public DBManager getDBManager(){
		return DBOfflineManager.getDBManager();
	}
	
	public void free(){
		if(this.netAnt != null){
			this.netAnt.free();
			System.gc();
		}
	}
	
	protected String getString(String src){
		return src.replaceAll("'", "’")
				  .replaceAll("\"", "”")
				  .replaceAll("&nbsp;", "")
				  .replaceAll("<br>", "")
				  .replaceAll("<br/>", "")
				  .replaceAll("<p>", "")
				  .replaceAll("</p>", "");
	}
	
	protected String getDateString(String name,char begin,char end){
		
		List<String> retList = new ArrayList<String>();
		StringBuffer sb = new StringBuffer();
		boolean flag = false;
		for(int i=0;i<name.length();i++){
			char active = name.charAt(i);		
			if(active == begin){
				flag = true;	
				sb = new StringBuffer();
			}else if(active == end){
				flag = false;
				retList.add(sb.toString());			
			}else{
				if(flag){
					sb.append(active);
				}
			}
		}
		
		String date = "";
		
		for(String active:retList){
			
			String num = active.trim();
			
			if(num.length()!=6){
				continue;
			}else{
				Pattern p1=Pattern.compile("^\\d*$"); 
				if(p1.matcher(num).lookingAt()){
					date = num;
					break;
				}
			}
		}
		
		if("".equals(date)){
			return "0000-00-00";
		}else{
			if(date.startsWith("0") || date.startsWith("1")|| date.startsWith("2")){
				date = "20"+date;
			}else{
				date = "19"+date;
			}
			return date.substring(0,4)+"-"+date.substring(4,6)+"-"+date.substring(6);
			
		}

	}
	
	public static String cutString(String name,char begin,char end){
		
		StringBuffer sb = new StringBuffer();
		boolean flag = true;
		for(int i=0;i<name.length();i++){
			char active = name.charAt(i);
			
			if(active == begin){
				flag = false;
			}else if(active == end){
				flag = true;
			}else{
				if(flag){
					sb.append(active);
				}
			}
			
		}
		
		return sb.toString();
		
	}
	
	public Elements select(String cssQuery){
		return document.select(cssQuery);
	}
	
}
